package com.example.k12.activity

import android.text.TextUtils
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.k12.bean.AuthInfoReq
import com.example.k12.bean.AuthInfoRes
import com.example.k12.bean.DeviceInfoBean
import com.example.k12.bean.Goods
import com.example.k12.bean.OrderReq
import com.example.k12.bean.OrderRes
import com.example.k12.bean.PayRes
import com.example.k12.bean.StudentInfo
import com.example.k12.bean.SyncStatisticsReq
import com.example.k12.http.NetworkRequest
import com.example.k12.http.component1
import com.example.k12.http.component2
import com.example.k12.http.safeApiCallWithCast
import com.example.k12.utlis.AppConfig
import com.example.k12.utlis.KeyManager
import com.example.k12.utlis.WxPayUtils
import com.example.k12.utlis.db.DBManager
import kotlinx.coroutines.launch

class MainViewModel : ViewModel() {

    var userInfo: StudentInfo? = null
    var totalAmount: Double = 0.01

    fun getDeviceInfo(callback: (String, Boolean) -> Unit) = viewModelScope.launch {
        val (deviceInfoBean, err) = safeApiCallWithCast<DeviceInfoBean> {
            NetworkRequest.api.getDeviceInfo(
                AppConfig.instance.deviceId
            )
        }
        if (deviceInfoBean != null) {
            // 获取成功，处理用户数据
            AppConfig.instance.token = deviceInfoBean.token
//            deviceInfoBean.deviceInfo.organizationId = "O161180Z0567577771"
            AppConfig.instance.deviceInfo = deviceInfoBean.deviceInfo
            callback("正在同步用户信息...", true)
            getAuthInfo(callback)
            syncStatistics()
        } else {
            // 获取失败，err 为错误描述
            LogUtils.e("获取设备信息失败：$err")
            callback("同步用户信息失败：${err?.message}", false)
        }

    }

    fun syncStatistics() = viewModelScope.launch {
        val (statisticsList, err) = safeApiCallWithCast<List<StudentInfo>> {
            NetworkRequest.api.syncStatisticsBySchoolId(
                SyncStatisticsReq(), AppConfig.instance.token
            )
        }
        if (!statisticsList.isNullOrEmpty()) {
            // 获取成功，处理用户数据
            if (statisticsList.isNotEmpty()) {
                SPUtils.getInstance().put(KeyManager.KEY_SYNC_TIME, System.currentTimeMillis())
                DBManager.getInstance().insertStatisticsBeans(statisticsList)
            } else {
                LogUtils.e("同步学生信息失败：学生信息为空")
            }
        } else {
            // 获取失败，err 为错误描述
            LogUtils.e("同步学生信息失败：$err")
        }
    }

    private fun getAuthInfo(callback: (String, Boolean) -> Unit) = viewModelScope.launch {
        if (TextUtils.isEmpty(AppConfig.instance.rawdata)) {
            callback("获取授权信息失败：微信SDK初始化失败", false)
            return@launch
        }
        val (authInfoRes, err) = safeApiCallWithCast<AuthInfoRes> {
            NetworkRequest.api.getAuthInfo(
                AuthInfoReq(), AppConfig.instance.token
            )
        }
        if (authInfoRes != null) {
            // 获取成功，处理用户数据
            LogUtils.e("获取授权信息成功：$authInfoRes")
            AppConfig.instance.authInfo = authInfoRes.authinfo
            WxPayUtils.manualUpdateFaceDatas()
        } else {
            // 获取失败，err 为错误描述
            LogUtils.e("获取授权信息失败：$err")
            callback("获取授权信息失败：${err?.message}", false)
        }
    }

    fun getUserInfo(userId: String, userName: (StudentInfo?, String) -> Unit) =
        viewModelScope.launch {
            if (!NetworkUtils.isConnected()) {
                getUserInfoEro(userId, userName)
                return@launch
            }
            val (studentInfo, err) = safeApiCallWithCast<StudentInfo> {
                NetworkRequest.api.getStudent(userId)
            }
            if (studentInfo != null) {
                DBManager.getInstance().insertOrUpdateStatisticsBean(studentInfo)
                checkUserInfo(studentInfo, userName)
            } else {
                // 获取失败，err 为错误描述
                LogUtils.e("获取学生信息失败：$err")
                getUserInfoEro(userId, userName)
            }
        }

    private fun getUserInfoEro(
        userId: String,
        userName: (StudentInfo?, String) -> Unit
    ) {
        if (AppConfig.instance.isToday()) {
            val studentInfo = DBManager.getInstance().queryStatisticsBeanById(userId)
            if (studentInfo == null) {
                userName(null, "获取学生信息失败：未能查询到学生信息")
            } else {
                checkUserInfo(studentInfo, userName)
            }
        } else {
            userName(null, "获取学生信息失败：未能查询到学生信息")
        }
    }

    fun checkUserInfo(
        studentInfo: StudentInfo, userName: (StudentInfo?, String) -> Unit
    ) {
        // 获取成功，处理用户数据
        userInfo = studentInfo
        if (studentInfo.status == 0) {
            userName(null, "该用户未激活")
            return
        }
        val checkMsg = studentInfo.canConsumeToday(totalAmount)
        if (!TextUtils.isEmpty(checkMsg)) {
            userName(null, checkMsg)
            return
        }
        userName(studentInfo, "")
    }

    fun toPay(payToken: String, payRes: (PayRes) -> Unit) = viewModelScope.launch {

        val studentId = userInfo?.uuid!!
        val goods =
            arrayListOf(Goods(number = (totalAmount / 0.01).toLong(), orderAmount = totalAmount))
        val orderReq = OrderReq(authCode = payToken, studentId = studentId, goodsList = goods)
        if (!NetworkUtils.isConnected() && AppConfig.instance.deviceInfo?.paymentMode != 1) {
            paySuc(
                payRes, studentId,
                OrderRes(
                    balanceAfter = (userInfo!!.balance - totalAmount),
                    orderAmount = totalAmount,
                    paymentMode = orderReq.paymentMode,
                    orderSource = "SUCCESS"
                )
            )
            return@launch
        }
        val (infoRes, err) = safeApiCallWithCast<OrderRes> {
            NetworkRequest.api.toPay(
                orderReq, AppConfig.instance.token
            )
        }
        if (infoRes != null) {
            // 获取成功，处理用户数据
            if (infoRes.orderSource == "SUCCESS") {
                paySuc(payRes, studentId, infoRes)
            }
        } else {
            // 获取失败，err 为错误描述
            LogUtils.e("提交订单失败：$err")
            if (AppConfig.instance.deviceInfo?.paymentMode != 1) {
                paySuc(
                    payRes, studentId,
                    OrderRes(
                        balanceAfter = (userInfo!!.balance - totalAmount),
                        orderAmount = totalAmount,
                        paymentMode = orderReq.paymentMode,
                        orderSource = "SUCCESS"
                    )
                )
            } else {
                showToast("提交订单失败：$err")
                payRes(PayRes(msg = "提交订单失败：${err?.message}", code = 1))
            }
        }
    }

    private fun paySuc(payRes: (PayRes) -> Unit, studentId: String, infoRes: OrderRes) {
        payRes(PayRes(msg = "支付成功", code = 0, data = infoRes))
        DBManager.getInstance().updateStatisticsBeanBalance(studentId, infoRes.balanceAfter)
    }


    private fun showToast(msg: String) {
        ToastUtils.showLong(msg)
    }
}

